package com.realgodo.site.service.relation;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.hibernate.DefaultEntityManager;

import com.realgodo.site.entity.relation.FriendCatalog;

@Service
@Transactional
public class FriendCatalogManager extends DefaultEntityManager<FriendCatalog, Long>{
	
	@Autowired
	protected SessionFactory sessionFactory;

	/**获取朋友分类*/
	@SuppressWarnings("unchecked")
	public List<FriendCatalog> getFriendCatalogList(Long spaceId){
		List<FriendCatalog> friendCatalogList =null;
		if(spaceId==null||DAFAULT_LONG_NULL_VALUE.equals(spaceId)){
			return new ArrayList<FriendCatalog>();
		}
		Criteria c = sessionFactory.getCurrentSession().createCriteria(FriendCatalog.class);
		c.add(Restrictions.eq("space.id", spaceId));
		c.addOrder(Order.desc("id"));
		friendCatalogList=c.list();
		if(friendCatalogList==null){
			friendCatalogList = new ArrayList<FriendCatalog>();
		}
		return friendCatalogList;
	}
	
	/**移出分类，并将朋友专致默认分类.createQuery("delete from DailyAttachment o where o.daily.id = ?")*/
	public boolean delete (Long spaceId,Long catalogId){
		if(spaceId==null||catalogId==null||DAFAULT_LONG_NULL_VALUE.equals(spaceId)||DAFAULT_LONG_NULL_VALUE.equals(catalogId)){
			return false;
		}
		//更形相关朋友分类信息,防止关联删除
		sessionFactory.getCurrentSession()
		.createQuery("update FriendConfig o set o.catalog.id = ? where o.onwer.id = ? and o.catalog.id = ?")
		.setParameter(0, FriendCatalog.DEFAULT)
		.setParameter(1, spaceId)
		.setParameter(2, catalogId)
		.executeUpdate();
		//删除分类
		this.delete(catalogId);
		return true;
	}
}
